package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.OperationConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.dto.mapper.SetmealDTOMapper;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.*;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.mapper.SetmealMapper;
import com.sky.vo.SetmealDishVO;
import com.sky.vo.SetmealVO;
import jakarta.validation.constraints.NotNull;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author luo20
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2025-07-06 16:37:49
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {

    private static final String OPERATION_INSERT = "INSERT";
    private static final String OPERATION_UPDATE = "UPDATE";


    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealDTOMapper setmealDTOMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageResult<SetmealVO> pageSetmeal(SetmealPageQueryDTO setmealPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        // 根据条件分页查询套餐数据
        List<SetmealVO> setmealVOList = setmealMapper.getSetmealPageByConditions(setmealPageQueryDTO);
        // 封装到page
        Page<SetmealVO> page = (Page<SetmealVO>) setmealVOList;
        // 返回结果
        return PageResult.<SetmealVO>builder()
                .total(page.getTotal())
                .records(page.getResult())
                .build();
    }
    //根据插入和更新操作判断执行检查分类状态和套餐内菜品状态
    public void checkCategoryAndDishStatus(SetmealDTO setmealDTO,String operationType) {
        // 根据插入还是更新来判断返回分类提示语
        String finalCategoryMessage;
        if (operationType.equals(OperationConstant.INSERT)){
            finalCategoryMessage = MessageConstant.BELONG_CATEGORY_DISABLED_INSERT;
        }else{
            finalCategoryMessage = MessageConstant.BELONG_CATEGORY_DISABLED_UPDATE;
        }
        // 根据插入还是更新来判断返回停售菜品提示语
        String finalSetmealMessage;
        if (operationType.equals(OperationConstant.INSERT)){
            finalSetmealMessage = MessageConstant.SETMEAL_INCLUDE_DISABLE_DISH_INSERT;
        }else{
            finalSetmealMessage = MessageConstant.SETMEAL_INCLUDE_DISABLE_DISH_UPDATE;
        }
        // 1. 检查分类状态
        Category category = categoryMapper.selectById(setmealDTO.getCategoryId());
        if (category == null || Objects.equals(category.getStatus(), StatusConstant.DISABLE)) {
            throw new AddSetmealFailException(finalCategoryMessage);
        }
        // 2. 检查套餐内菜品状态
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (CollectionUtils.isNotEmpty(setmealDishes)) {
            // 获取所有菜品ID
            List<Long> dishIds = setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList());
            // 查询这些菜品
            List<Dish> dishList = dishMapper.selectByDishIds(dishIds);
            // 检查是否有停售菜品
            List<String> disabledDishNames = new ArrayList<>();
            // 把停售的菜品名称添加到disabledDishNames中
            dishList.forEach(dish -> {
                if (Objects.equals(dish.getStatus(), StatusConstant.DISABLE)) {
                    disabledDishNames.add(dish.getName());
                }
            });
            if (!disabledDishNames.isEmpty()) {
                String dishNames = StringUtils.join(disabledDishNames, "、");
                throw new AddSetmealFailException(MessageFormat.format(finalSetmealMessage,dishNames));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSetmeal(SetmealDTO setmealDTO) {
        //根据插入和更新操作判断执行检查分类状态和套餐内菜品状态是否符合要求
        checkCategoryAndDishStatus(setmealDTO,OPERATION_INSERT);
        // dto转entity
        Setmeal setmeal = setmealDTOMapper.toEntity(setmealDTO);
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        // 新增套餐
        Integer setmealResult = setmealMapper.saveSetmeal(setmeal);
        // 判断套餐是否已经添加成功
        if (setmealResult <= 0) {
            // 套餐新增失败
            throw new AddSetmealFailException(MessageConstant.SETMEAL_ADD_FAILD);
        }
        // 判断setmealDishList不为空
        if (CollectionUtils.isNotEmpty(setmealDishList)) {
            // 把套餐id关联到到setmealDish中
            setmealDishList.forEach(sd -> sd.setSetmealId(setmeal.getId()));
            // 新增菜品与套餐的联系
            Integer setmealDishResult = setmealDishMapper.saveBatchSetmealDish(setmealDishList);
            // 判断套餐与菜品的联系是否添加成功
            if (setmealDishResult <= 0) {
                // 套餐与菜品的联系新增失败
                throw new AddSetmealDishFailException(MessageConstant.SETMEAL_DISH_ADD_FAILD);
            }
        }
    }

    @Override
    public SetmealVO getSetmealById(Long id) {
        return setmealMapper.getSetmealById(id);
    }

    @Override
    public void updateSetmeal(SetmealDTO setmealDTO) {
        //根据插入和更新操作判断执行检查分类状态和套餐内菜品状态是否符合要求
        checkCategoryAndDishStatus(setmealDTO,OPERATION_UPDATE);
        //dto转entity
        Setmeal setmeal = setmealDTOMapper.toEntity(setmealDTO);
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        // 更新套餐
        Integer setResult = setmealMapper.updateSetmealById(setmeal);
        // 判断套餐是否更新成功
        if (setResult <= 0) {
            throw new SetmealUpdateErrorException(MessageConstant.SETMEAL_UPDATE_FAILD);
        }
        //获取setmealId
        Long setmealId = setmeal.getId();
        // 根据setmealId判断套餐与菜品关系不为空
        List<SetmealDish> setmealDishes = setmealDishMapper.selectSetmealDishBySetmealId(setmealId);
        if (CollectionUtils.isNotEmpty(setmealDishes)){
            // 再先删除套餐与菜品的关联
            Integer delSetmealDishResult = setmealDishMapper.delSetmealDishById(setmeal.getId());
            // 判断是否删除成功
            if (delSetmealDishResult <= 0) {
                throw new DeletionSetmealDishErrorException(MessageConstant.SETMEAL_DISH_DELETE_FAILD);
            }
        }
        //判断前端传来的套餐与菜品数据是否为空
        //不为空
        if (CollectionUtils.isNotEmpty(setmealDishList)) {
            //将套餐id与菜品关联起来
            setmealDishList.forEach(sd -> sd.setSetmealId(setmealId));
            // 更新新的套餐与菜品的关联
            Integer saveBatchSetmealDishResult = setmealDishMapper.saveBatchSetmealDish(setmealDishList);
            // 判断是否添加成功
            if (saveBatchSetmealDishResult <= 0){
                throw new AddSetmealDishFailException(MessageConstant.SETMEAL_DISH_UPDATE_FAILD);
            }
        }
    }

    @Override
    public void startOrStopStatus(Integer status, Long id) {
        // 如果是要启售套餐，需要检查菜品状态
        if (status.equals(StatusConstant.ENABLE)) {
            // 查询套餐信息获取分类ID
            Setmeal setmeal = setmealMapper.selectById(id);
            if (setmeal != null) {
                // 查询分类状态
                Category category = categoryMapper.selectById(setmeal.getCategoryId());
                if (category == null || !Objects.equals(category.getStatus(), StatusConstant.ENABLE)) {
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_BELONG_CATEGORY_DISABLED);
                }
            }
            // 根据套餐id查询菜品
            List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishBySetmealId(id);
            if (CollectionUtils.isNotEmpty(setmealDishList)) {
                // 获取所有菜品id
                List<Long> dishIdList = setmealDishList.stream().map(SetmealDish::getDishId).collect(Collectors.toList());
                // 根据菜品id查询所有菜品状态
                List<Dish> dishList = dishMapper.selectByDishIds(dishIdList);

                // 收集所有未起售菜品的名称
                List<String> disabledDishNames = new ArrayList<>();
                for (Dish dish : dishList) {
                    if (Objects.equals(dish.getStatus(), StatusConstant.DISABLE)) {
                        disabledDishNames.add(dish.getName());
                    }
                }
                // 如果有未起售菜品，则抛出异常
                if (!disabledDishNames.isEmpty()) {
                    String dishNames = StringUtils.join(disabledDishNames, "、");
                    throw new SetmealEnableFailedException(MessageFormat.format(MessageConstant.SETMEAL_ENABLE_FAILED,dishNames));
                }
            }else {
                // 该套餐下没有菜品，无法启售,请添加菜品！
                throw new SetmealEnableFailedException(MessageConstant.SETMEAL_UNDER_NODISHES_THEN_NOT_ENABLE);
            }
        }
        Setmeal setmeal = new Setmeal()
                .setId(id)
                .setStatus(status);
        // 更新套餐状态
        Integer updSetmealStatusResult = setmealMapper.updSetmealStatusById(setmeal);
        // 判断是否更新成功
        if (updSetmealStatusResult <= 0){
            throw new UpdateStatusErrorException(MessageConstant.UPDATE_STATUS_FAILED);
        }
    }

    @Override
    public void deleteBatchByIds(List<Long> ids) {
        // 判断套餐id是否为空
        if (CollectionUtils.isEmpty(ids)) {
            // ids为空
            throw new SetmealIdsEmptyException(MessageConstant.SETMEAL_ID_NOT_FOUND);
        }
        //根据套餐id查询套餐数据
        List<Setmeal> setmealList = setmealMapper.selectBatchBySetmealIds(ids);
        //删除前判断是否启售
        setmealList.stream().filter(setmeal -> setmeal.getStatus().equals(StatusConstant.ENABLE))
                .forEach(setmeal -> {
                    //如果启售则抛出异常，套餐启售则不能删除
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ON_SALE);
                });
        // 根据套餐id查询套餐与菜品关系数据
        List<SetmealDish> setmealDishList = setmealDishMapper.selectBatchSetmealDishBySetmealIds(ids);
        // 判断是否关联了菜品
        if (CollectionUtils.isNotEmpty(setmealDishList)) {
            // 关联了则删除套餐菜品数据
            Integer delResult = setmealDishMapper.delBatchSetmealDishByIds(ids);
            if (delResult <= 0) {
                throw new DeletionSetmealDishErrorException(MessageConstant.SETMEAL_DISH_DELETE_FAILD);
            }
        }
        // 根据套餐id删除套餐数据
        Integer delResult = setmealMapper.delBatchSetmealByIds(ids);
        if (delResult <= 0) {
            throw new DeletionNotAllowedException(MessageConstant.DELETE_FAILED);
        }
    }

    @Override
    public List<Setmeal> getSetmealByCategoryId(Long categoryId) {
        Setmeal setmeal = new Setmeal()
                .setCategoryId(categoryId)
                .setStatus(StatusConstant.ENABLE);
        return setmealMapper.selectByCategoryConditions(setmeal);
    }

    @Override
    public List<SetmealDishVO> getSetmealDishBySetmealId(Long id) {
        //判断套餐下的菜品描述是否为null，为null则返回暂无菜品描述
        return setmealDishMapper.selectSetmealDishAndDishBySetmealId(id)
                .stream()
                .peek(setmealDishVO -> {
                    // 判断菜品描述是否为null，为null则返回暂无菜品描述
                    if (StringUtils.isBlank(setmealDishVO.getDescription())){
                        setmealDishVO.setDescription(MessageConstant.DISH_DESCRIPTION_NULL);
                    }
                })
                .collect(Collectors.toList());
    }


}




